#!/bin/bash

set -e

<%
  require "cgi"
  require "shellwords"

  def esc(x)
    Shellwords.shellescape(x)
  end

  if !spec.address or spec.address == ""
    peer_ip = "127.0.0.1"
  else
    peer_ip = spec.address
  end

  atc_url = nil
  if_link("atc") do |atc|
    atc.instances.each do |instance|
      atc_url = "http://#{instance.address}:#{atc.p("bind_port")}"
    end
  end
  atc_url ||= "#{p("atc.url")}"

  teamAuthorizedKeys = Hash.new
  p("team_authorized_keys").each do |a|
    teamName = a["team"]
    keys = teamAuthorizedKeys[teamName]
    if keys == nil
      keys = [a["ssh_key"]]
    else
     keys.push(a["ssh_key"])
   end

    teamAuthorizedKeys[teamName] = keys
  end
%>

RUN_DIR=/var/vcap/sys/run/tsa
LOG_DIR=/var/vcap/sys/log/tsa
PIDFILE=$RUN_DIR/tsa.pid
SIGNING_KEY=/var/vcap/packages/generated_signing_key/id_rsa

source /var/vcap/packages/pid_utils/pid_utils.sh

case $1 in

  start)
    pid_guard $PIDFILE "tsa"

    mkdir -p $RUN_DIR
    chown -R vcap:vcap $RUN_DIR

    mkdir -p $LOG_DIR
    chown -R vcap:vcap $LOG_DIR

    echo $$ > /var/vcap/sys/run/tsa/tsa.pid

    for key in /var/vcap/packages/generated_tsa_host_key/id_rsa \
               /var/vcap/jobs/tsa/config/host_key \
               $SIGNING_KEY; do
      chown vcap:vcap $key
      chmod 0400 $key
    done

    {
<% if p("authorize_generated_worker_key") %>
      cat /var/vcap/packages/generated_worker_key/id_rsa.pub
<% end %>
      cat <<EOF
<%= p("authorized_keys").join("\n") %>
EOF
    } > /var/vcap/jobs/tsa/config/authorized_keys

<% teamAuthorizedKeys.each do |team, keys| %>
    {
      cat <<EOF
<%= keys.join("\n") %>
EOF
    } > /var/vcap/jobs/tsa/config/<%= team %>_authorized_keys
 <% end %>

    # TODO: TSA should support multiple ATCs
    exec chpst -u vcap:vcap /var/vcap/packages/tsa/bin/tsa \
      --atc-url <%= atc_url %> \
      --peer-ip <%= peer_ip %> \
      --bind-port <%= p("bind_port") %> \
      <% if p("host_key") != "" %> \
      --host-key /var/vcap/jobs/tsa/config/host_key \
      <% else %> \
      --host-key /var/vcap/packages/generated_tsa_host_key/id_rsa \
      <% end %> \
      --authorized-keys /var/vcap/jobs/tsa/config/authorized_keys \
      <% teamAuthorizedKeys.each do |team, keys| %> \
      --team-authorized-keys <%= team %>=/var/vcap/jobs/tsa/config/<%= team %>_authorized_keys \
       <% end %> \
      --session-signing-key $SIGNING_KEY \
      --heartbeat-interval <%= p("heartbeat_interval") %> \
      --yeller-api-key <%= esc(p("yeller.api_key")) %> \
      --yeller-environment <%= esc(p("yeller.environment_name")) %> \
      1>>$LOG_DIR/tsa.stdout.log \
      2>>$LOG_DIR/tsa.stderr.log

    ;;

  stop)
    kill_and_wait $PIDFILE

    ;;

  *)
    echo "Usage: $0 {start|stop}"

    ;;

esac
